package com.aide.simplification.popedom.popedom;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.directwebremoting.annotations.RemoteMethod;
import org.directwebremoting.annotations.RemoteProxy;

import com.aide.simplification.global.GlobalConfig;
import com.aide.simplification.global.Utils;
import com.aide.simplification.popedom.login.LoginUser;
import com.aide.simplification.popedom.login.PopSSO;
import com.aide.simplification.popedom.popedom.base.BasePop;

/**
 * 用户管理
 * 
 * @author sorc
 * 
 */
//@Component("User")
//@RemoteProxy(creator = SpringCreator.class, creatorParams = @Param(name = "beanName", value = "User"), name = "User")
@RemoteProxy(name="User") 
public class User extends BasePop {

	String userinfo = " useruuid, username, name, pop, state,email,userlevel ";

	/**
	 * 分页查询所有用户
	 * 
	 * @param page
	 * @param size
	 * @return
	 */
	@RemoteMethod
	public List<Map<String, Object>> findAllUserPage(int page, int size) {
		String sql = dbop.initPageSql(page, size, "useruuid", "select "
				+ userinfo + " from pop_user");
		List<Map<String, Object>> list = dbop.queryForList(sql);
		for (int i = 0; i < list.size(); i++) {
			Map<String, Object> hm = list.get(i);
			hm.put("role", this.findRoleNameByUserUUID(hm.get("useruuid")
					.toString()));
			hm.put("dept", this.findDeptNameByUserUUID(hm.get("useruuid")
					.toString()));
			list.set(i, hm);
		}
		return list;

	}

	/**
	 * 分页查询此部门所有用户
	 * 
	 * @param page
	 * @param size
	 * @param deptid
	 * @return
	 */
	public List<Map<String, Object>> findAllUserPageByDept(String deptid,
			int page, int size) {
		String sql = "SELECT pop_user_dept.deptid, pop_user.useruuid, pop_user.username, pop_user.name, pop_user.pop, pop_user.state FROM pop_user INNER JOIN pop_user_dept ON pop_user.useruuid = pop_user_dept.useruuid WHERE (pop_user_dept.deptid = '"
				+ deptid + "')";
		sql = dbop.initPageSql(page, size, "useruuid", sql);
		List<Map<String, Object>> list = dbop.queryForList(sql);

		for (int i = 0; i < list.size(); i++) {
			// HashMap hm = (HashMap) list.get(i);
			// hm.put("role", this.findRoleNameByUserUUID(hm.get("useruuid")
			// .toString()));
			// hm.put("dept", this.findDeptNameByUserUUID(hm.get("useruuid")
			// .toString()));
			// list.set(i, hm);
		}
		return list;
	}

	/**
	 * 分页查询此角色所有用户
	 * 
	 * @param page
	 * @param size
	 * @param deptid
	 * @return
	 */
	public List<Map<String, Object>> findAllUserPageByRole(int page, int size,
			String roleid) {
		String sql = "SELECT pop_user_role.roleid, pop_user.useruuid, pop_user.username, pop_user.name, pop_user.pop, pop_user.state FROM pop_user INNER JOIN pop_user_role ON pop_user.useruuid = pop_user_role.useruuid WHERE (pop_user_role.roleid = '"
				+ roleid + "')";
		sql = dbop.initPageSql(page, size, "useruuid", sql);
		List<Map<String, Object>> list = dbop.queryForList(sql);
		// for (int i = 0; i < list.size(); i++) {
		// Map hm = (Map) list.get(i);
		// hm.put("role", this.findRoleNameByUserUUID(hm.get("useruuid")
		// .toString()));
		// hm.put("dept", this.findDeptNameByUserUUID(hm.get("useruuid")
		// .toString()));
		// list.set(i, hm);
		// }
		return list;
	}

	@RemoteMethod
	public List<Map<String, Object>> findUserByLikeUserNamePrepareCall(
			String username, String name, int begin, int end,
			HttpServletRequest request, HttpServletResponse response) {

		String useruuid = "";
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		PopSSO sso = new PopSSO(request, response);
		LoginUser lu = sso.ssoSync();
		if (lu != null) {
			useruuid = lu.getUseruuid();
			String sql = "{ call getDeptUser(?,?,?,?) }";
			Object[] obj = { useruuid, 0, begin, end };
			list = dbop.prepareCallForList(sql, obj);
		}
		return list;
	}

	@RemoteMethod
	public List<Map<String, Object>> findUserByLikeUserName(String username,
			String name, int page, int pagesize, HttpServletRequest request,
			HttpServletResponse response) {
		int begin = (page - 1) * pagesize;
		//int end = pagesize;
		String useruuid = "";
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		PopSSO sso = new PopSSO(request, response);
		LoginUser lu = sso.ssoSync();
		if (lu != null) {
			useruuid = lu.getUseruuid();
			if (useruuid.equals(Utils.getConfig("pop.admin"))) {
				String sql0 = "select * from pop_user where username like  '"
						+ username + "%' and name like  '%" + name + "%'";
				sql0 = dbop.initPageSql(page, pagesize, "useruuid", sql0);
				return dbop.queryForList(sql0);
			} else {
				String sql = "select deptid from pop_user_dept where useruuid=? and useruuid<>?";
				List<Map<String, Object>> deptlist = dbop.queryForList(sql,
						new Object[] { useruuid, Utils.getConfig("pop.admin") });

				for (Iterator<Map<String, Object>> iterator = deptlist
						.iterator(); iterator.hasNext();) {
					Map<String, Object> map = iterator.next();
					String subdeptid = map.get("deptid").toString();
					String sql1 = "select u.*,d.deptid deptid from pop_dept d,pop_user_dept ud,pop_user u where ud.deptid=d.deptid and ud.useruuid=u.useruuid and d.deptid='"
							+ subdeptid
							+ "' and u.username like  '"
							+ username
							+ "%' and u.name like  '%"
							+ name
							+ "%' and u.useruuid<>'" + Utils.getConfig("pop.admin") + "'";
					list.addAll(dbop.queryForList(sql1));
					list.addAll(this.findUserByDept(username, name, subdeptid));
				}
				int bi = begin >= 0 ? begin : 0;
				int ei = (page * pagesize + 1) < list.size() ? (page * pagesize + 1)
						: list.size();
				list = list.subList(bi, ei);
			}
		}
		return list;
	}

	@RemoteMethod
	public int getCountUserByLikeUserName(String username, String name,
			HttpServletRequest request, HttpServletResponse response) {
		String useruuid = "";
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		PopSSO sso = new PopSSO(request, response);
		LoginUser lu = sso.ssoSync();
		if (lu != null) {
			useruuid = lu.getUseruuid();
			if (useruuid.equals(Utils.getConfig("pop.admin"))) {
				String sql0 = "select count(*) from pop_user where username like ? and name like ?";
				return dbop.queryForInt(sql0, new Object[] { username + "%",
						name + "%" });
			}

			String sql = "select deptid from pop_user_dept where useruuid=? and useruuid<>?";
			List<Map<String, Object>> deptlist = dbop.queryForList(sql,
					new Object[] { useruuid, Utils.getConfig("pop.admin") });
			for (Iterator<Map<String, Object>> iterator = deptlist.iterator(); iterator
					.hasNext();) {
				Map<String, Object> map = iterator.next();
				String subdeptid = map.get("deptid").toString();
				String sql1 = "select u.useruuid,u.username,u.name,u.state,d.deptid from pop_dept d,pop_user_dept ud,pop_user u where ud.deptid=d.deptid and ud.useruuid=u.useruuid and d.deptid=? and u.username like ? and u.name like ? and u.useruuid<>?";
				list.addAll(dbop.queryForList(sql1,new Object[]{subdeptid,username+"%",name+"%",Utils.getConfig("pop.admin")}));
				list.addAll(this.findUserByDept(username, name, subdeptid));
			}
		}
		return list.size();
	}

	public List<Map<String, Object>> findUserByDept(String username,
			String name, String deptid) {
		String sql = "select u.useruuid,u.username,u.name,u.state,d.deptid deptid from pop_dept d,pop_user_dept ud,pop_user u where ud.deptid=d.deptid and ud.useruuid=u.useruuid and d.mdeptid=? and username like ? and name like ? and u.useruuid<>?";
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		list = dbop.queryForList(sql,new Object[]{deptid,username+"%",name+"%",Utils.getConfig("pop.admin")});
		List<Map<String, Object>> alllist = new ArrayList<Map<String, Object>>();
		if (list != null) {
			for (Iterator<Map<String, Object>> iterator = list.iterator(); iterator.hasNext();) {
				Map<String, Object> map =  iterator.next();
				String subdeptid = map.get("deptid").toString();
				alllist.add(map);
				alllist.addAll(this.findUserByDept(username, name, subdeptid));
			}
		}
		return alllist;
	}

	/**
	 * 查询所有用户
	 * 
	 * @return
	 */
	@RemoteMethod
	public List<Map<String, Object>> findAllUser() {
		String sql = "select " + userinfo + " from pop_user";
		List<Map<String, Object>> list = dbop.queryForList(sql);
		for (int i = 0; i < list.size(); i++) {
			Map<String, Object> hm =  list.get(i);
			hm.put("role", this.findRoleNameByUserUUID(hm.get("useruuid")
					.toString()));
			hm.put("dept", this.findDeptNameByUserUUID(hm.get("useruuid")
					.toString()));
			list.set(i, hm);
		}
		return list;
	}

	/**
	 * 查询所有可用用户
	 * 
	 * @return
	 */
	public List<Map<String, Object>> findAllUserState() {
		String sql = "select " + userinfo + " from pop_user where state=1";
		List<Map<String, Object>> list = dbop.queryForList(sql);
		for (int i = 0; i < list.size(); i++) {
			Map<String, Object> hm =  list.get(i);
			hm.put("role", this.findRoleNameByUserUUID(hm.get("useruuid")
					.toString()));
			hm.put("dept", this.findDeptNameByUserUUID(hm.get("useruuid")
					.toString()));
			list.set(i, hm);
		}
		return list;
	}

	/**
	 * 新建用户
	 * 
	 * @param username
	 * @param name
	 * @param password
	 * @param dept
	 * @param sign
	 * @param role
	 * @return
	 */
	@RemoteMethod
	public int addUser(String username, String name, String password,
			String state,String email, HttpServletRequest request,
			HttpServletResponse response) {
		String curruserid = "";

		int flag = 0;
		PopSSO sso = new PopSSO(request, response);
		LoginUser lu = sso.ssoSync();
		if (lu != null) {
			curruserid = lu.getUseruuid();
			List<Map<String, Object>> list = dbop.queryForList("select deptid from pop_user_dept where useruuid=?",new Object[]{curruserid});
			if (list != null && list.size() > 0) {
				Map<String, Object> hm = new HashMap<String, Object>();
				hm.put("username", username);
				hm.put("name", name);
				hm.put("password", password);
				hm.put("state", state);
				String useruuid = Utils.getUUID();
				hm.put("useruuid", useruuid);
				hm.put("pop", "0");
				hm.put("email", email.trim());
				hm.put("userlevel", "0");
				hm.put("version", "0");
				flag = dbop.save("pop_user", hm);
				for (Iterator<Map<String, Object>> iterator = list.iterator(); iterator
						.hasNext();) {
					String deptid = iterator.next().get("deptid").toString();
					Map<String, Object> udhm = new HashMap<String, Object>();
					udhm.put("useruuid", useruuid);
					udhm.put("deptid", deptid);
					udhm.put("version", "0");
					dbop.save("pop_user_dept", udhm);
				}
				return 1;
			} else {
				return -1;
			}
		}
		return flag;
	}

	/**
	 * 添加/修改组织机构角色
	 * 
	 * @param deptid
	 * @param roleids
	 * @return
	 */
	@RemoteMethod
	public int addRoles(String useruuid, String[] roleids, String[] nroleids) {
		UserRole ur = new UserRole();
		// 删除此人员的未选中角色角色
		for (int i = 0; i < nroleids.length; i++) {
			String roleid = nroleids[i];
			ur.removeByUserUUIDRoleid(useruuid, roleid);
		}

		// 删除此人员的选中角色
		for (int i = 0; i < roleids.length; i++) {
			String roleid = roleids[i];
			ur.removeByUserUUIDRoleid(useruuid, roleid);
		}
		int rolesize = roleids.length;
		int flag = 0;
		for (int i = 0; i < rolesize; i++) {
			String roleid = roleids[i];
			flag += ur.newUserRole(roleid, useruuid);
		}
		if (flag == rolesize) {
			flag = 1;
		}
		String sqluserLevel = "select max(pr2.roleLevel) from pop_user_role as pur2,pop_role as pr2 where pur2.roleid=pr2.roleid and pur2.useruuid=?";
		List<Map<String, Object>> list = dbop.queryForList(sqluserLevel,new Object[]{useruuid});
		if (list == null || list.size() < 1) {
			sqluserLevel = "update pop_user set pop_user.userLevel='0' where pop_user.useruuid =?";
		} else {
			sqluserLevel = "update pop_user set pop_user.userLevel=(";
			sqluserLevel += "select max(pr2.roleLevel) from pop_user_role as pur2,pop_role as pr2 where pur2.roleid=pr2.roleid and pur2.useruuid=pop_user.useruuid)";
			sqluserLevel += " where pop_user.useruuid =?";
		}
		dbop.executeUpdate(sqluserLevel,new Object[]{useruuid});

		ur.reComputePop(useruuid);// 更新此人员权限
		return flag;
	}

	/**
	 * 更新用户信息
	 * 
	 * @param useruuid
	 * @param name
	 * @param dept
	 * @param state
	 * @param role
	 * @return
	 */
	@RemoteMethod
	public int updateUser(String useruuid, String name, String state,String email) {
		Map<String, Object> hm = new HashMap<String, Object>();
		hm.put("name", name);
		hm.put("state", state);
		hm.put("email", email.trim());
		int flag = 0;
		flag = dbop.update("pop_user", hm, "useruuid", useruuid);
		return flag;
	}

	/**
	 * 修改密码
	 * 
	 * @param useruuid
	 * @param name
	 * @param dept
	 * @param state
	 * @param role
	 * @return
	 */
	@RemoteMethod
	public int updateUserPassword(String username, String password) {
		Map<String, Object> hm = new HashMap<String, Object>();
		hm.put("password", password);
		int flag = 0;
		flag = dbop.update("pop_user", hm, "username", username);
		return flag;
	}

	/**
	 * 更新用户信息
	 * 
	 * @param useruuid
	 * @param name
	 * @param dept
	 * @param state
	 * @param role
	 * @return
	 */
	@RemoteMethod
	public int updateUserByUserName(String username, String name, String email) {
		Map<String, Object> hm = new HashMap<String, Object>();
		hm.put("name", name);
		hm.put("email", email);
		int flag = 0;
		flag = dbop.update("pop_user", hm, "username", username);
		return flag;
	}

	/**
	 * 初始化密码
	 * 
	 * @param useruuid
	 * @return
	 */
	@RemoteMethod
	public int initPassword(String useruuid) {
		String password="";
		try{
			GlobalConfig gc = new GlobalConfig();
			password = gc.getString("pop.initpassword");
		}catch (Exception e) {
			password="123456";
		}
		String sql="update pop_user set password=? where useruuid=?";
		return dbop.executeUpdate(sql,new Object[]{password,useruuid});
	}

	/**
	 * 获得用户总数
	 * 
	 * @return
	 */
	@RemoteMethod
	public int getCount() {
		return dbop.queryForInt("select count(useruuid) from pop_user");
	}

	/**
	 * 按用户统一编号删除用户
	 * 
	 * @param useruuid
	 * @return
	 */
	@RemoteMethod
	public int removeUserById(String useruuid) {
		UserDept ud = new UserDept();
		ud.removeByUserUUID(useruuid);// 及联删除用户部门关系
		UserRole ur = new UserRole();
		ur.removeByUserUUID(useruuid);// 及联删除用户角色关系
		return dbop.delete("pop_user", "useruuid", useruuid);
	}

	/**
	 * 按用户统一编号删除用户
	 * 
	 * @param useruuid
	 * @return
	 */
	@RemoteMethod
	public int removeUserByUserName(String username) {
		String useruuid = dbop.queryForString("pop_user", "useruuid","username", username);
		UserDept ud = new UserDept();
		ud.removeByUserUUID(useruuid);// 及联删除用户部门关系
		UserRole ur = new UserRole();
		ur.removeByUserUUID(useruuid);// 及联删除用户角色关系
		return dbop.delete("pop_user", "useruuid", useruuid);
	}

	/**
	 * 按照用户统一编号获得权限名称
	 * 
	 * @param useruuid
	 * @return
	 */
	@RemoteMethod
	public String findRoleNameByUserUUID(String useruuid) {
		String sql = "SELECT pop_role.rolename AS role ";
		sql += " FROM pop_user_role INNER JOIN ";
		sql += " pop_role ON pop_user_role.roleid = pop_role.roleid RIGHT OUTER JOIN ";
		sql += " pop_user ON pop_user_role.useruuid = pop_user.useruuid";
		sql += " WHERE (pop_user.useruuid = ?)";
		List<Map<String, Object>> list = dbop.queryForList(sql,new Object[]{useruuid});
		String role = "";
		for (int i = 0; i < list.size(); i++) {
			Map<String, Object> hm =  list.get(i);
			if (hm.get("role") != null) {
				role += hm.get("role").toString() + ";";
			}
		}
		return role;
	}

	/**
	 * 按照用户统一编号获得部门名称
	 * 
	 * @param useruuid
	 * @return
	 */
	@RemoteMethod
	public String findDeptNameByUserUUID(String useruuid) {
		String sql = "SELECT pop_dept.dept AS dept ";
		sql += " FROM pop_user_dept INNER JOIN ";
		sql += " pop_dept ON pop_user_dept.deptid = pop_dept.deptid RIGHT OUTER JOIN ";
		sql += " pop_user ON pop_user_dept.useruuid = pop_user.useruuid";
		sql += " WHERE (pop_user.useruuid = ?)";
		List<Map<String, Object>> list = dbop.queryForList(sql,new Object[]{useruuid});
		String dept = "";
		for (int i = 0; i < list.size(); i++) {
			Map<String, Object> hm =  list.get(i);
			if (hm.get("dept") != null) {
				dept += hm.get("dept").toString() + ";";
			}
		}
		return dept;
	}

	/**
	 * 查询此用户所在组织机构
	 * 
	 * @param useruuid
	 * @return
	 */
	@RemoteMethod
	public List<Map<String, Object>> findDeptidByUserUUID(String useruuid) {
		UserDept ud = new UserDept();
		return ud.findByUserUUID(useruuid);
	}

	public List<Map<String, Object>> findByUserUUIDAllInfo(String useruuid) {
		UserDept ud = new UserDept();
		return ud.findByUserUUIDAllInfo(useruuid);
	}

	public List<Map<String, Object>> findByUserUUIDIsUseInfo(String useruuid) {
		UserDept ud = new UserDept();
		return ud.findByUserUUIDIsUseInfo(useruuid);
	}

	/**
	 * 查询此用户所有角色
	 * 
	 * @param useruuid
	 * @return
	 */
	@RemoteMethod
	public List<Map<String, Object>> findRoleidByUserUUID(String useruuid) {
		UserRole ur = new UserRole();
		return ur.findByUserUUID(useruuid);
	}

	/**
	 * 按照主键查询
	 * 
	 * @param pkvalue
	 * @return
	 */
	public Map<String, Object> findByPk(String pkvalue) {
		return dbop.findByPK("pop_user", "useruuid", pkvalue);
	}
	public int update(Map<String,Object> hm,String pkvalue) {
		return dbop.update("pop_user", hm,"useruuid",pkvalue);
	}
	/**
	 * 检查用户名是否重复
	 * 
	 * @param username
	 * @return
	 */
	@RemoteMethod
	public int checkUsername(String username) {
		if (username.indexOf("'") != -1 || username.length() <= 0) {
			return 0;
		}
		if (dbop.queryForInt("select count(*) from pop_user where username=?",new Object[]{username}) > 0) {
			return 0;
		}
		return 1;
	}

	/**
	 * 为用户添加/修改所属组织机构
	 * 
	 * @param useruuid
	 * @param deptids
	 * @return
	 */
	@RemoteMethod
	public int addDepts(String useruuid, String deptids) {
		UserDept ud = new UserDept();
		ud.removeByUserUUID(useruuid);
		int flag = 0;
		if (deptids.equals("")) {
			return 1;
		} else {
			String[] deptid = deptids.split(",");
			for (int j = 0; j < deptid.length; j++) {
				String dept = deptid[j];
				flag += ud.newUserDept(dept, useruuid);
			}
			if (flag == deptid.length) {
				flag = 1;
			}
		}
		return flag;
	}

	/**
	 * 查询用户并分页显示
	 * 
	 * @param username
	 * @param name
	 * @param page
	 * @param size
	 * @return
	 */
	@RemoteMethod
	public List<Map<String, Object>> searchUser(String username, String name,
			int page, int size) {
		String sql = "select " + userinfo
				+ " from pop_user where username like '" + username
				+ "%' and name like '%" + name + "%'";
		sql = dbop.initPageSql(page, size, "useruuid", sql);
		return dbop.queryForList(sql);
	}

	/**
	 * 查询到的用户数
	 * 
	 * @param username
	 * @param name
	 * @return
	 */
	@RemoteMethod
	public int searchUserGetCount(String username, String name) {
		String sql = "select count(*) from pop_user where username like ? and name like ?";
		return dbop.queryForInt(sql,new Object[]{username+"%","%"+name+"%"});
	}

	/**
	 * 察看用户信息
	 * 
	 * @param pkvalue
	 * @return
	 */
	@RemoteMethod
	public List<Map<String, Object>> chakan(String pkvalue) {
		Map<String, Object> hm = findByPk(pkvalue);
		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		if (hm != null) {
			Map<String, Object> hm0 = new HashMap<String, Object>();
			hm0.put("title", "用户编号:");
			hm0.put("tname", "useruuid");
			hm0.put("tvalue", hm.get("useruuid").toString());
			list.add(hm0);
			Map<String, Object> hm1 = new HashMap<String, Object>();
			hm1.put("title", "用户名:");
			hm1.put("tname", "username");
			hm1.put("tvalue", hm.get("username").toString());
			list.add(hm1);
			Map<String, Object> hm2 = new HashMap<String, Object>();
			hm2.put("title", "姓名:");
			hm2.put("tname", "name");
			hm2.put("tvalue", hm.get("name").toString());
			list.add(hm2);
			Map<String, Object> hm4 = new HashMap<String, Object>();
			hm4.put("title", "email:");
			hm4.put("tname", "email");
			hm4.put("tvalue", hm.get("email").toString());
			list.add(hm4);
			Map<String, Object> hm3 = new HashMap<String, Object>();
			hm3.put("tname", "state");
			hm3.put("tval", hm.get("state").toString());
			hm3.put("title", "有效标记:");
			if (hm.get("state").toString().equals("1")) {
				hm3.put("tvalue", "可用");
			} else {
				hm3.put("tvalue", "不可用");
			}
			list.add(hm3);
		}
		return list;
	}

	public List<Map<String, Object>> findByLevel(int level, String opsign) {
		String sql = "select " + userinfo + " from pop_user where userLevel "
				+ opsign + "?";
		return dbop.queryForList(sql,new Object[]{level});
	}

	public List<Map<String, Object>> findUserByUserUP(String useruuid) {
		return pc.getUpUserByUser(useruuid);
	}

	public List<Map<String, Object>> findUserByUserDown(String useruuid) {
		return pc.getDownUserByUser(useruuid);
	}
	public Map<String, Object> checkLogin (String username, String password){
		Map<String, Object> hm = new HashMap<String, Object>();
		hm.put("username", username);
		hm.put("password", password);
		return dbop.findByPK("pop_user", hm);
	}
}
